package com.tomorrow.analyze;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.R.string;
import android.content.res.Resources;

import com.tomorrow.weather.application.WeatherApplication;
import com.tomorrow.weather.entity.City;
import com.tomorrow.weather.mInterface.IHotCityData;
import com.tomorrow.weather.ui.R;

public class HotCityDataSax implements IHotCityData
{
	private ArrayList<City> hotCities;

	@Override
	public List<City> getHotCity()
	{
		InputStream is = null;

		Resources resources = (WeatherApplication.getContext()).getResources();
		is = resources.openRawResource(R.raw.hot_city);

		SAXParserFactory factory = SAXParserFactory.newInstance();
		try
		{
			SAXParser parser = factory.newSAXParser();
			ParseSAX handler = new ParseSAX();
			parser.parse(is, handler);

		}
		catch (ParserConfigurationException e)
		{

			e.printStackTrace();
		}
		catch (SAXException e)
		{

			e.printStackTrace();
		}
		catch (IOException e)
		{

			e.printStackTrace();
		}
		finally
		{
			if (is != null)
			{
				try
				{
					is.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		return hotCities;
	}

	class ParseSAX extends DefaultHandler
	{
		private City city;

		@Override
		public void startDocument() throws SAXException
		{
			hotCities = new ArrayList<City>();
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException
		{
			System.out.println(localName);
			if ("string".equals(localName))
			{
				city = new City();
				city.setCityId(attributes.getValue(0));
				System.out.println(attributes.getValue(0));
			}

		}

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException
		{
			if (length > 1)
			{
				String cityName = new String(ch, start, length);
				city.setCityName(cityName);

			}

		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException
		{
			if ("string".equals(localName))
			{
				hotCities.add(city);
			}

		}

	}

}
